package com.heima.leadnews.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.leadnews.admin.mapper.AdLoginMapper;
import com.heima.leadnews.admin.service.AdLoginService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.login.dto.AdUserDto;
import com.heima.model.login.pojo.AdUser;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录
 */
@Service
@Transactional
public class AdLoginServiceImpl extends ServiceImpl<AdLoginMapper,AdUser> implements AdLoginService {


    /**
     * 登录功能
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1，判断数据是否为空
        if(dto==null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2,用户名或密码不能为空
        if(StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名或密码不能为空");
        }

        //3，用户不存在
        LambdaQueryWrapper<AdUser> userLambdaQw=new LambdaQueryWrapper<>();
        userLambdaQw.eq(AdUser::getName,dto.getName());
        AdUser user = getOne(userLambdaQw);
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //4,密码错误

        //用户登录明文密码
        String loginPwd = dto.getPassword();
        //随机盐
        String dbSalt = user.getSalt();
        //明文和随机盐生产的密码
        String pwd=loginPwd+dbSalt;
        //加密后的密码
        String pwdEncrypt = DigestUtils.md5DigestAsHex(pwd.getBytes());

        //获取数据库密码
        String dbPassword = user.getPassword();

        if (dbPassword.equals(pwdEncrypt)){
            //5登录成功
            Map userMap=new HashMap<>();
            String token = AppJwtUtil.getToken(user.getId().longValue());
            userMap.put("token",token);
            userMap.put("user",user);
            user.setPassword("");
            user.setSalt("");
            return ResponseResult.okResult(userMap);
        }
        //密码错误
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
    }


    /**
     * 用户注册功能
     * @param user
     * @return
     */
    @Override
    public ResponseResult register(AdUser user) {
        //1,判断用户是否为空
        if(user==null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1.1判断数据库是否存在该用户和手机号
        LambdaQueryWrapper<AdUser> adUserLambdaQw=new LambdaQueryWrapper<>();
        adUserLambdaQw.eq(AdUser::getName,user.getName());
        adUserLambdaQw.eq(AdUser::getPhone,user.getPhone());
        AdUser one = getOne(adUserLambdaQw);
        if(one!=null){
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST);
        }

        //2，设置密码加密为MD5（密码+salt）
        String salt = RandomStringUtils.randomAlphanumeric(10);
        String pwd=user.getPassword();
        //密码+salt
        String saltEncrypt=salt+pwd;
        String pwdEncrypt = DigestUtils.md5DigestAsHex(saltEncrypt.getBytes());
        user.setPassword(pwdEncrypt);
        //设置主键自增

        user.setName(user.getName());
        user.setSalt(salt);
        user.setNickname(user.getNickname());
        user.setImage(user.getImage());
        user.setPhone(user.getPhone());
        user.setStatus(user.getStatus());
        user.setLoginTime(new Date());
        user.setCreatedTime(new Date());

        //3,添加到数据库
        save(user);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
